const fs = require('fs')
const app = require('electron').app
const remote = require('electron').remote
const RULES = '/static/store/rules.json';
const CONFIG = '/static/store/config.json';

function  Store () {

    this.getAppPath = () => {
        if (app) {
            return app.getAppPath();
        } else {
            return remote.app.getAppPath();
        }
    };
    /**
     * load rules store from local storage.
     */
    this.loadRules = () =>  {
        var data = fs.readFileSync(`${this.getAppPath()}/${RULES}`, 'utf-8');
        if (data != null) {
            return JSON.parse(data);
        } else {
            return [];
        }
    };

    this.loadConfig = () => {
        var data = fs.readFileSync(`${this.getAppPath()}/${CONFIG}`, 'utf-8');
        if (data != null) {
            return JSON.parse(data);
        } else {
            return {};
        }
    };

    this.updateConfig = (newConfig) => {
        fs.writeFileSync(`${this.getAppPath()}/${CONFIG}`, JSON.stringify(newConfig));
    };

    /**
     * update rules
     */
    this.updateRules = (newItem) => {
        var data = fs.readFileSync(`${this.getAppPath()}/${RULES}`)
        var dataObj = JSON.parse(data);
        if (!newItem.id) {
            newItem.id = this.guid();
            dataObj.push(newItem);
        } else {
            for (let i=0; i<dataObj.length; i++) {
                if (newItem.id === dataObj[i].id) {
                    dataObj[i] = Object.assign({}, newItem);
                }
            }
        }
        
        var newData = JSON.stringify(dataObj)
        fs.writeFileSync(`${this.getAppPath()}/${RULES}`, newData);
    };

    this.removeRule =  (guid) =>  {
        var data = this.loadRules();
        if (null != data) {
            var newData = [];
            for (let index = 0; index < data.length; index++) {
                const element = data[index];
                if (element.id != guid) {
                    newData.push(element);
                } 
            }
            if (newData != null) {
                fs.writeFileSync(`${this.getAppPath()}/${RULES}`, JSON.stringify(newData));
            }
        }
    };
    // uuid generation
    this.S4 = () =>  {
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    this.guid = () => {
        return (this.S4()+this.S4()+"-"+this.S4()+"-"+this.S4()+"-"+this.S4()+"-"+this.S4()+this.S4()+this.S4());
    };
}

module.exports = Store